package com.zheng.coderepo.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Redis频率限制。
 * Created by zhangchaozheng on 16-7-28.
 */
public class RedisFrequencyLimit {

    private JedisPool jedisPool;

    public RedisFrequencyLimit(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    /**
     * 检查频率限制。
     *
     * @param limitKey
     * @param limitation
     * @throws FrequencyLimitException
     */
    public void checkLimit(String limitKey, String limitation) throws FrequencyLimitException {
        FrequencyExpr frequencyExpr = FrequencyExpr.parseLimitation(limitation);
        Jedis jedis = jedisPool.getResource();
        try {
            String countStr = jedis.get(limitKey);
            int current = (countStr == null) ? 0 : Integer.parseInt(countStr);
            if (current >= frequencyExpr.getRate()) {
                throw new FrequencyLimitException("Exceed limits, current: " + current);
            }
            long next = jedis.incr(limitKey);
            if (next == 1L) {
                jedis.expire(limitKey, frequencyExpr.getDurationSeconds());
            }
        } finally {
            quietlyCloseJedis(jedis);
        }
    }

    /**
     * 关闭redis连接。jedis 3.0开始，官方抛弃了原来的returnResource和returnBrokenResource。
     *
     * @param jedis
     */
    private void quietlyCloseJedis(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
}
